package com.dx.mes.service.webservice.service;

import com.dx.common.table.his.His_ret_prd_info;
import com.dx.common.table.ppt.Bis_data;
import com.dx.common.table.ppt.Ret_wo;
import com.dx.common.table.ppt.Trans_prd_sap;
import com.dx.mes.common.bean.erp.EWORDER;
import com.dx.mes.common.core.rabbitmq.BaseConnFactory;
import com.dx.mes.common.dao.IBisDataDao;
import com.dx.mes.common.dao.IHisRetPrdInfoDao;
import com.dx.mes.common.dao.IRetWODao;
import com.dx.mes.common.dao.ITransPrdSapDao;
import com.dx.mes.common.transcoder.util.GUIDGenerator16;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.webservice.tx.Msapwork.Key;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.dx.mes.common.bean.def.GenericDef.EVT_MES_SAP_WORK;


/**
 * Created by admin on 2018/3/31.
 */
@Service("msapworkService")
public class MsapworkService {

    @Autowired
    private IHisRetPrdInfoDao hisRetPrdInfoDao;
    @Autowired
    private IBisDataDao bisDataDao;
    @Autowired
    private ITransPrdSapDao transPrdSapDao;
    @Autowired
    private IRetWODao retWoDao;
    @Resource
    private BaseConnFactory baseConnFactory;

    public void subMainProc() {

        //获得所有报工站点
        String sql ="select data_ext from  bis_data  where data_cate='DWPR' and ext_4='Y'";

        List<String> sapWork= bisDataDao.findBySQL(sql);

        List<His_ret_prd_info> his_ret_prd_infoAll = new  ArrayList<>();//所有的报工屏体
        for(String ope:sapWork){
            //获得这个报工站点的上一次报工时间
            String sqlM = "select * from trans_prd_sap where ope_id_fk = '" +ope+"' and evt_cate='MSWK'";
            List<Trans_prd_sap> sapList = transPrdSapDao.findBySQL(sqlM,Trans_prd_sap.class);

            if(sapList!=null && sapList.size()>0){
                Trans_prd_sap trans_prd_sap = sapList.get(0);
                Format dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date  = dateFormat.format(trans_prd_sap.getMes_update_time());
                String hql ="FROM His_ret_prd_info where cr_ope_id_fk='" +ope+"' and evt_cate='LGOF'" +
                        " and evt_timestamp > to_date('" +date+"','yyyy-mm-dd hh24:mi:ss')";
                List<His_ret_prd_info> his_ret_prd_infos = hisRetPrdInfoDao.find(hql);
                his_ret_prd_infoAll.addAll(his_ret_prd_infos);
            }else {//该站点第一次报工
                String hql ="FROM His_ret_prd_info where cr_ope_id_fk='" +ope+"' and evt_cate='LGOF'";
                List<His_ret_prd_info> his_ret_prd_infos = hisRetPrdInfoDao.find(hql);
                his_ret_prd_infoAll.addAll(his_ret_prd_infos);
            }
        }
        Map<Key,List<His_ret_prd_info>> map = new HashMap<>();
        for(His_ret_prd_info  his_ret_prd_info : his_ret_prd_infoAll){
            Key key = new Key();
            key.setCr_ope_id_fk(his_ret_prd_info.getCr_ope_id_fk());
            key.setWo_id_fk(his_ret_prd_info.getWo_id_fk());
            if(map.containsKey(key)){
                map.get(key).add(his_ret_prd_info);
            }else {
                 List<His_ret_prd_info> list = new ArrayList<>();
                list.add(his_ret_prd_info);
                map.put(key,list);
            }
        }
        List<EWORDER> eworderList = new ArrayList<EWORDER>();
        Map<String,Trans_prd_sap>  transMap = new HashMap<>();
        Format dateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = dateFormat.format(new Date());
        Format dateFormat1 = new SimpleDateFormat("HHmmss");
        String time = dateFormat1.format(new Date());
        Timestamp current_timestamp = Util.getCurrentTimestamp();
        for(Map.Entry<Key, List<His_ret_prd_info>> entry : map.entrySet()){
        	EWORDER eworder = new EWORDER();
        	eworder.setAUFNR(entry.getKey().getWo_id_fk());
            Ret_wo ret_wo = retWoDao.get(entry.getKey().getWo_id_fk());
            if(ret_wo!=null){
            	eworder.setMATNR(ret_wo.getMdl_id_fk());
                String sqlN ="select * from bis_data where data_cate='DWPR' and ext_2='" + ret_wo.getMdl_id_fk() + "' and data_ext='" +entry.getKey().getCr_ope_id_fk()+"'";
                List<Bis_data> opeList = bisDataDao.findBySQL(sqlN,Bis_data.class);
                if (opeList!=null && opeList.size()>0){
                	eworder.setVORNR(opeList.get(0).getExt_5());
                }
                eworder.setIEDZ(time);
                eworder.setIEDD(date);
                //报工数量和返工数量和半成品数量
                List<String> prdSeqId = null;
                String sqls = "select * from trans_prd_sap where ope_id_fk = '" +entry.getKey().getCr_ope_id_fk()+"' and evt_cate='MSWK'";
                List<Trans_prd_sap> sapList = transPrdSapDao.findBySQL(sqls,Trans_prd_sap.class);
                if(sapList!=null && sapList.size()>0){//正常过账条数
                    Trans_prd_sap trans_prd_sap = sapList.get(0);
                    Format dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date2 = dateFormat2.format(trans_prd_sap.getMes_update_time());
                    String hqlA ="select distinct prd_seq_id FROM His_ret_prd_info where cr_ope_id_fk='" +entry.getKey().getCr_ope_id_fk()+"' and evt_cate='LGOF'" +
                            " and wo_id_fk='" +entry.getKey().getWo_id_fk()+"' and evt_timestamp > to_date('" +date2+"','yyyy-mm-dd hh24:mi:ss')";
                     prdSeqId = hisRetPrdInfoDao.find(hqlA);
                }else {//正常过账条数
                    String hqlA ="select distinct prd_seq_id FROM His_ret_prd_info where cr_ope_id_fk='" +entry.getKey().getCr_ope_id_fk()+"' and wo_id_fk='" +entry.getKey().getWo_id_fk()+"' and evt_cate='LGOF'";
                    prdSeqId = hisRetPrdInfoDao.find(hqlA);
                }
                eworder.setLMNGA(String.valueOf(prdSeqId.size()));//报工数量
                eworder.setMENGE("0");//半成品数量
                //同工单某一站点，总共LGOf数量 -  正常LGOF数量= 返工次数
                int reQty = entry.getValue().size()-prdSeqId.size();
                eworder.setRMNGA(String.valueOf(reQty));//返工数量
                eworderList.add(eworder);
                //
                Trans_prd_sap trans_prd_sap = null;
                String sqlM = "select * from trans_prd_sap where  ope_id_fk = '" +entry.getKey().getCr_ope_id_fk()+"' and evt_cate='MSWK'";
                List<Trans_prd_sap> opelist = transPrdSapDao.findBySQL(sqlM,Trans_prd_sap.class);
                if(opelist!=null && opelist.size()>0){
                    trans_prd_sap = opelist.get(0);
                    trans_prd_sap.setOpe_id_fk(entry.getKey().getCr_ope_id_fk());
                    trans_prd_sap.setMes_update_time(current_timestamp);
                    trans_prd_sap.setPrd_qty(Integer.valueOf(entry.getValue().size()));
                    if (opeList!=null && opeList.size()>0){
                        trans_prd_sap.setSap_id(opeList.get(0).getExt_5());
                    }
                    trans_prd_sap.setEvt_usr("MES");
                    trans_prd_sap.setEvt_cate(EVT_MES_SAP_WORK);//报工操作
                    trans_prd_sap.setEvt_timestamp(current_timestamp);
                    transMap.put(entry.getKey().getCr_ope_id_fk(),trans_prd_sap);
                }else {
                    trans_prd_sap  =  new Trans_prd_sap();
                    trans_prd_sap.setEvt_seq_id(GUIDGenerator16.javaGUID());
                    trans_prd_sap.setOpe_id_fk(entry.getKey().getCr_ope_id_fk());
                    if (opeList!=null && opeList.size()>0){
                        trans_prd_sap.setSap_id(opeList.get(0).getExt_5());
                    }
                    trans_prd_sap.setPrd_qty(Integer.valueOf(entry.getValue().size()));
                    trans_prd_sap.setMes_update_time(current_timestamp);
                    trans_prd_sap.setEvt_usr("MES");
                    trans_prd_sap.setEvt_cate(EVT_MES_SAP_WORK);//报工操作
                    trans_prd_sap.setEvt_timestamp(current_timestamp);
                    transMap.put(entry.getKey().getCr_ope_id_fk(),trans_prd_sap);
                }
            }
        }
        for(Map.Entry<String, Trans_prd_sap> entry : transMap.entrySet()){
           transPrdSapDao.saveOrUpdate(entry.getValue());
        }
        
        try {
            if(eworderList.size()>0){
//                baseConnFactory.addSAPREQProc("EWORDER", JacksonUtil.toJSONStr(eworderList));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
